import { Component, ElementRef, Input, OnInit, ViewChild, Injectable } from '@angular/core';
import { PurchaseListService } from "./purchase-list.service";
import { InquiryStatusComponent } from "../inquiry-status/inquiry-status.component";
import { ConsultingPriceComponent } from "../consulting-price/consulting-price.component";
import { AppPaginationComponent, PaginationModel } from '../../../../widgets/pagination/pagination.component';
import { environment } from '../../../../../environments/environment';
import { Util } from "../../../../common/util";
import * as _ from 'lodash'

/**
 * 
 */
@Component({
  selector: 'new-stock-purchase-purchase-list',
  templateUrl: './purchase-list.component.html',
  styleUrls: ['./purchase-list.component.scss'],
  providers: [PurchaseListService]
})
export class PurchaseListComponent implements OnInit {
  _ = _;

  @Input()
  public data: Array<any>;

  public modalStatus: boolean;

  // 新股列表
  public newStockList: Array<any> = [];

  // 查询条件
  public searchBody:any = {
    vcNewstockId: "", // 证券代码
    vcNewstockStatus: "", // 状态
    page: 1 // 页码
  }

  // 新股询价基金列表 key- 实例ID，value- 申购详情列表
  // [{
  //   lNewstockNo: 询价详情数组:[]
  // }]
  public SGList: any = {};

  // 新股发起询价的新股ID
  public lNewstockNo: any = "";

  public newStockIdPara;

  public statusPara;

  // 分页配置
  public pageInfo: PaginationModel = {
    currentPageNum: 1,
    totalPages: 1,
    total: 0 // 总记录数
  }

  // 分页组件
  @ViewChild("newStockPag")
  public paginationComponent: AppPaginationComponent;

  // 询价分页配置
  // {
  //   lNewstockNo ： 分页配置 PaginationModel
  // }
  public sgPageInfo: any = {}

  // 询价分页配置
  @ViewChild("sgPag")
  private sgPaginationComponent: AppPaginationComponent;

  // 询价列表查询条件
  public sgSearchBody = {
    page: "1",
    pageSize: environment.pageSize,
    vcFundCode: "",
    vcNewstockId: "",
    vcOperaterId: "",
    vcFundmrgId: ""
  }

  // 下一处理状态
  @ViewChild(InquiryStatusComponent)
  private inquiryStatusComponent: InquiryStatusComponent;

  // 询价
  @ViewChild(ConsultingPriceComponent)
  private consultingPriceComponent: ConsultingPriceComponent;


  @ViewChild("modal")
  public modal: ElementRef;

  // 新股状态
  public newStockStatus: any;

  constructor(public purchaseListService: PurchaseListService) {
    this.getStatusDir();
    this.getNewstockList(1);
  }

  ngOnInit() {
  }

  public openPurchaseListModal(lNewstockNo){
    this.consultingPriceComponent.openModal('2',lNewstockNo);
  }

  public openModal(): void {
    this.modalStatus = true;
    Util.$(this.modal.nativeElement).modal('show');
  }

  public closeModal(): void {
    this.modalStatus = false;
    Util.$(this.modal.nativeElement).modal('hide');
  }

  public toggleModal(): void {
    this.modalStatus = !this.modalStatus;
    Util.$(this.modal.nativeElement).modal('toggle');
  }

  /**
   * [search 查询]
   */
  search() {
    this.getNewstockList(1);
  }

  /**
   * [resetSearch 重置查询条件]
   */
  resetSearch() {
    this.searchBody = {
      vcNewstockId: "", // 证券代码
      vcNewstockStatus: "", // 状态
      page: 1 // 页码
    }
  }

  /**
   * [getNewstockList 新股列表]
   */
  public getNewstockList(pageNum) {

    this.searchBody.page = pageNum;

    this.purchaseListService.getNewstockList(this.searchBody).subscribe(data => {
      this.SGList = {}; // 重置

      if (data) {
        this.newStockList = data.list;

        // 添加是否选择属性
        _.forEach(this.newStockList, data => {
          data.isChecked = false;
        })

        // 构建分页
        this.pageInfo.currentPageNum = data.pageNum;
        this.pageInfo.totalPages = data.pages;
        this.pageInfo.total = data.total; // 总记录数
      }

      console.log(JSON.stringify(this.newStockList));
    });
  }

  /**
   * [getSGListById 申购基金列表]
   * @param {[type]} lNewstockNo [格式：实例ID'-'选择的页码]
   * @param index 索引
   * @param closeList 关闭列表
   */
  public getSGListById(lNewstockNoAndPageNum,index,closeList) {
    var oNAndNumList = _.split(lNewstockNoAndPageNum, '-');
    var lNewstockNo = oNAndNumList[0]; // 实例ID
    var pageNum = "1";


    // 选择状态
    var newStock = _.find(this.newStockList, { lNewstockNo: _.toNumber(lNewstockNo) });

    if(closeList){
      window["$"]("#sg"+index).slideToggle();
      newStock.isChecked = !newStock.isChecked;
    }

    // 展开状态
    if (newStock.isChecked == true) {
      if (oNAndNumList.length > 1) {
        pageNum = oNAndNumList[1]; //选择的页码
      }

      this.sgSearchBody.page = pageNum;

      this.purchaseListService.getSGList(this.sgSearchBody, lNewstockNo).subscribe(data => {
        if (data) {
          this.SGList[lNewstockNo] = data.list;

          // 构建分页
          var temp = {
            currentPageNum: data.pageNum,
            totalPages: data.pages,
          }
          this.sgPageInfo[lNewstockNo] = temp;
        }

      });
    }
  }

  /**
   * [initSG 初始化申购数据]
   * @param {[type]} lNewstockNo [实例ID]
   */
  initSG(lNewstockNo) {
    var param = {
      lNewstockNo: lNewstockNo, // 实例Id
    }

    this.purchaseListService.initSG(param).subscribe(data => {
      if (data) {
        window["swal"]("初始化成功", "", "success");
        this.getNewstockList(1); // 刷新
      }
    });
  }


  /**
   * [switchNewStockStatus 根据新股状态码，返回中文]
   * @param {[type]} num [新股状态码]
   */
  switchNewStockStatus(num) {
    var retVal = "";

    var status: any = _.find(this.newStockStatus, { vcItemKey: num });
    if (status) {
      retVal = status.vcItemValue;
    }

    return retVal;
  }

  /**
   * [getStatusDir 获取业务状态字典]
   */
  getStatusDir() {
    this.purchaseListService.getStatusDir({}).subscribe(data => {
      this.newStockStatus = data;
    });
  }

  /**
   * [getSGCurPage 当前页面编码]
   * @param {[type]} lNewstockNo [新股实例ID]
   */
  getSGCurPage(lNewstockNo) {
    if (!this.sgPageInfo[lNewstockNo]) {
      this.sgPageInfo[lNewstockNo] = {
        currentPageNum: 1,
        totalPages: 1,
      }
    }

    return this.sgPageInfo[lNewstockNo].currentPageNum;
  }

  /**
   * [getSGTotalPage 获得总记录数]
   * @param {[type]} lNewstockNo [新股实例ID]
   */
  getSGTotalPage(lNewstockNo) {
    if (!this.sgPageInfo[lNewstockNo]) {
      this.sgPageInfo[lNewstockNo] = {
        currentPageNum: 1,
        totalPages: 1,
      }
    }

    return this.sgPageInfo[lNewstockNo].totalPages;
  }

  /**
   * [reflesh 刷新列表]
   * @param {[type]} event [是否需要刷新]
   */
  reflesh(event?) {
    if (event) {
      this.resetSearch();
      this.getNewstockList(1);
    }
  }

  /**
   * 根据页码请求查询相关配置列表数据,如果当前活动页码就是目标页码，则不进行任何查询
   * 直接返回
   * @param {currentPageNum}
   */
  public pageNavigation(currentPageNum: number) {
    this.pageInfo.currentPageNum = currentPageNum;
    this.searchBody = {};
    this.getNewstockList(currentPageNum);
  }
  
}
